<?php

require_once "./PHPExcel.php";
require_once "../RedisDB.php";

$start_time = microtime(true);  // 

$redis = new RedisDB();

// 4. 保存在php://temp
$cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_to_phpTemp;
$cacheSettings = array('memoryCacheSize'=>'1024MB');
PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);

$objPHPExcel = new PHPExcel();
$objSheet = $objPHPExcel->getActiveSheet();
$objSheet->setTitle("spider");

$head = array(
    'id',
    'uid',
    'username',
    'code_age',
    'raw_count',
    'fans_count',
    'hot_count',
    'comment_count',
    'visit_count',
    'jifen_count',
    'collect_count',
    'week_ranking',
    'total_ranking',
    'blog_level'
);

// 设置表头
foreach($head as $index => $value){
    $ascll_A = ord("A");
    $objSheet->setCellValue(chr($ascll_A + $index) . "1", $value);   
}

$start = 0;
$end = $redis->getTotal() + 2; // 631957 内存溢出
// $end = 110000;  // 内存溢出
// $end = 11000;
// $end = 50000;


// echo $end, PHP_EOL;

$cur_row = 2;
// 从redis读取数据写入excel
for($i=$cur_row; $i<$end; $i++){
    $index = $i - 2;
    if($i % 100 == 0){
        $uid = $redis->getUid($index);
        $info = $redis->getInfo($uid);

        // echo "uid:{$uid}",PHP_EOL;
        // var_dump($info);
        // echo "---------------------------------------",PHP_EOL;

    
        if(!empty($info)){
            if(!empty($info['uid'])){
                // 编号
                $objSheet->setCellValue("A" . $cur_row, $index + 1);
                // 用户信息列
                $cursor = 1;
                $ascll_A = ord("A");
                foreach($info as $key=>$value){    
                    $objSheet->setCellValue(chr($ascll_A + $cursor) . $cur_row, $value);
                    $cursor ++;
                }
                $cur_row ++;
            }       
        
        }
    }

    if($i % 1000 == 0){
        echo "【当前：{$i}】", PHP_EOL,PHP_EOL;
    }

}


$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, "Excel2007");
$objWriter->save("./test.xlsx");

$cost_time = microtime(true) - $start_time;

// $s = round($cost_time)/1000;
$s = $cost_time;

echo "导出{$cur_row}条数据，用了{$s}秒",PHP_EOL;


exit(0);
